package com.demo.scenic.controller;

import com.demo.scenic.common.BaseResponse;
import com.demo.scenic.domain.dto.UserDTO;
import com.demo.scenic.service.UserService;
import com.demo.scenic.shiro.AccountProfile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = "login")
@RestController
@RequestMapping("/auth")
@AllArgsConstructor
public class LoginController {
    // private final Logger logger = LoggerFactory.getLogger(LoginController.class);
    private final UserService userService;

    @PostMapping("/login")
    @ApiOperation(value = "登录",notes = "登录")
    public BaseResponse login(@RequestBody UserDTO user) throws Exception{
        return userService.login(user);
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册",notes = "注册")
    public BaseResponse register(@Validated @RequestBody UserDTO user) throws Exception{
        return BaseResponse.ok(userService.register(user));
    }

    @RequiresAuthentication
    @GetMapping("/getUserInfo")
    @ApiOperation(value = "获取用户信息",notes = "获取用户信息")
    public BaseResponse getUserInfo(){
        AccountProfile accountRealm = (AccountProfile) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        return userService.getUserInfo(accountRealm);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出登录",notes = "退出登录")
    @RequiresAuthentication
    public BaseResponse logout(){
        SecurityUtils.getSubject().logout();
        return BaseResponse.ok("退出登录成功");
    }
    @GetMapping("/becomeBusiness")
    @ApiOperation(value = "成为商家",notes = "成为商家")
    @RequiresAuthentication
    public BaseResponse becomeBusiness(){
        AccountProfile accountRealm = (AccountProfile) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        return userService.becomeBusiness(accountRealm);
    }

    // 修改用户名
    @PostMapping("/updateUsername")
    @ApiOperation(value = "updateUsername",notes = "修改用户名")
    public BaseResponse updateUsername(@Param("username")String username){
        AccountProfile accountRealm = (AccountProfile) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        return userService.updateUserName(accountRealm,username);
    }

    // 修改用户头像
    @PostMapping("/updateAvatar")
    @ApiOperation(value = "updateAvatar",notes = "修改用户头像")
    public BaseResponse updateAvatar(@Param("avatar")String avatar){
        AccountProfile accountRealm = (AccountProfile) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        return userService.updateUserAvatar(accountRealm,avatar);
    }

}
